

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="CodeHope">
  <meta name="author" content="CodeHope">
  <meta name="keywords" content="希望">
  <title>对JavaScript中异步的理解 - CodeHope</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      
        
          
          
          
        
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/themes/prism-tomorrow.min.css" />
      
      
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/plugins/line-numbers/prism-line-numbers.min.css" />
      
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"quancundexiwang.wang","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":true,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"onlypost":true},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz","app_key":"hMuhiD4FRqhns4giqLiEH9HG","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
  <header style="height: 80vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>CodeHope</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                村头
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                我
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607883890412&di=04a28d2b70f12c8687f732ffe4bd796c&imgtype=0&src=http%3A%2F%2Fdingyue.nosdn.127.net%2FTwxMux86LVeJ3WfIvurVjTMAXfCI77QnkPeK%3DsHaVVHmM1535118627022.jpg') repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="对JavaScript中异步的理解">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-08-31 17:51" pubdate>
        2020年8月31日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      30
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">对JavaScript中异步的理解</h1>
            
            <div class="markdown-body">
              <h2 id="1-异步概述"><a href="#1-异步概述" class="headerlink" title="1.异步概述"></a>1.异步概述</h2><p>Javascript语言的执行环境是<code>&quot;单线程&quot;（single thread）。</code></p>
<p>所谓”单线程”，就是指<code>一次只能完成一件任务</code>。如果有<code>多个任务</code>，就<code>必须排队</code>，前面一个任务完成，再执行后面一个任务，以此类推。</p>
<p>这种模式的优缺点：</p>
<ul>
<li><p>优点</p>
<ul>
<li>实现起来比较简单</li>
<li>执行环境相对单纯</li>
</ul>
</li>
<li><p>缺点</p>
<ul>
<li>只要有一个任务耗时很长，后面的任务都必须排队等着，会拖延整个程序的执行。常见的浏览器无响应（假死），往往就是因为某一段Javascript代码长时间运行（比如死循环），导致整个页面卡在这个地方，其他任务无法执行。</li>
</ul>
</li>
</ul>
<p><strong>为了解决这个问题➡️</strong><br>Javascript语言将任务的执行模式分成两种：<font style="color:red">同步（Synchronous）</font>和<font style="color:red">异步（Asynchronous）</font>。</p>
<p><strong>同步模式：</strong></p>
<blockquote>
<p>后一个任务等待前一个任务结束，然后再执行，程序的执行顺序与任务的排列顺序是一致的、同步的；</p>
</blockquote>
<p><strong>异步模式</strong></p>
<blockquote>
<p>每一个任务有一个或多个回调函数（callback），前一个任务结束后，不是执行后一个任务，而是执行回调函数，后一个任务则是不等前一个任务结束就执行，所以程序的执行顺序与任务的排列顺序是不一致的、异步的。</p>
</blockquote>
<blockquote>
<p>“异步模式”非常重要。在浏览器端，耗时很长的操作都应该异步执行，避免浏览器失去响应，最好的例子就是Ajax操作。在服务器端，”异步模式”甚至是唯一的模式，因为执行环境是单线程的，如果允许同步执行所有http请求，服务器性能会急剧下降，很快就会失去响应</p>
</blockquote>
<p>异步机制</p>
<blockquote>
<p>（1）所有同步任务都在主线程上执行，行成一个执行栈<br> （2）主线程之外，还存在一个任务队列，只要异步任务有了结果，就会在任务队列中放置一个事件<br> （3）一旦执行栈中的所有同步任务执行完毕，系统就会读取任务队列，看看里面还有哪些事件，那些对应的异步任务，于是结束等待状态，进入执行栈，开始执行<br> （4）主线程不断的重复上面的第三步</p>
</blockquote>
<hr>


<p><font style="color:red"><strong>1.回调函数</strong></font></p>
<p>假定有两个函数f1和f2，f2需要f1的执行结果来执行自己的代码，但是f1是一个很耗时的任务，可以考虑改写f1，把f2写成f1的回调函数。</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">function</span> <span class="token function">f1</span><span class="token punctuation">(</span><span class="token parameter">callback</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>

　　　　<span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

　　　　　　<span class="token comment">// f1非常耗时的任务代码</span>

　　　　　　<span class="token function">callback</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

　　　　<span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

　　<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>执行代码就变成下面这样：</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">f1</span><span class="token punctuation">(</span>f2<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></div>
<p>采用这种方式，我们把同步操作变成了异步操作，<code>异步操作将会被放入任务队列</code>，等待同步代码执行完成之后，再去执行相应的耗时操作，也不会影响代码的执行顺序。</p>
<p>回调函数的优点是简单、容易理解和部署，缺点是不利于代码的阅读和维护，各个部分之间高度耦合（Coupling），流程会很混乱，而且每个任务只能指定一个回调函数。</p>
<p><font style="color:red"><strong>2.Promise</strong></font></p>
<p> Promise包括以下几个规范</p>
<p>一个promise可能有三种状态：<code>等待（pending）</code>、<code>已完成（fulfilled）</code>、<code>已拒绝（rejected）</code></p>
<p>一个promise的状态只可能从<code>“等待”转到“完成”态或者“拒绝”态，</code>不能逆向转换，同时“完成”态和“拒绝”态不能相互转换<br>promise必须实现then方法（可以说，then就是promise的核心），而且then必须返回一个promise，同一个promise的then可以调用多次，并且回调的执行顺序跟它们被定义时的顺序一致<br>then方法接受两个参数，第一个参数是成功时的回调，在promise由“等待”态转换到“完成”态时调用，另一个是失败时的回调，在promise由“等待”态转换到“拒绝”态时调用，同时，then可以接受另一个promise传入，也接受一个“类then”的对象或方法，即thenable对象</p>
<p><strong>在使用Promise时，我们需要检测一些浏览器是否支持Promise</strong></p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">typeof</span><span class="token punctuation">(</span>Promise<span class="token punctuation">)</span><span class="token operator">===</span><span class="token string">"function"</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"支持"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"不支持"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>


<p><strong>我们可以使用new Promise进行Promise的创建</strong></p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">function</span> <span class="token function">wait</span><span class="token punctuation">(</span><span class="token parameter">time</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span>reject</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">setTimeout</span><span class="token punctuation">(</span>resolve<span class="token punctuation">,</span>time<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><strong>这个时候我们就可以使用Promise处理异步任务啦</strong></p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">wait</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></div>
<blockquote>
<p>注：资料参考 <a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html">http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html</a></p>
</blockquote>
<h2 id="2-宏任务和微任务"><a href="#2-宏任务和微任务" class="headerlink" title="2.宏任务和微任务"></a>2.宏任务和微任务</h2><blockquote>
<p>从上面的知识我们知道，耗时操作都被放入异步操作中去，这里我们使用任务的思维来考虑整个过程<br><img src="http://qiniuyun.quancundexiwang.wang/20200903130423.png" srcset="/img/loading.gif"><br>当主线程的任务执行完了(执行栈空了)，JS会去轮询事件队列</p>
</blockquote>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token operator">&lt;</span>script<span class="token operator">></span>
    <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"定时器任务"</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">)</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"同步代码"</span><span class="token punctuation">)</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>script<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>虽然我们知道JavaScript代码都是<code>按照从上到下顺序执行，</code><br>但是<code>对于一些耗时操作</code>，JavaScript给你了<code>一种异步思路来防止因为耗时而造成的页面阻塞</code></p>
<p>异步代码 会被放到一个<code>任务队列</code>中，当同步代码执行完毕之后，然后去<code>任务队列中执行耗时的代码。</code><br>所以定时器中的代码是在同步代码执行完成之后才会被执行的。<br>那么上面执行的结果就是：<br><img src="http://qiniuyun.quancundexiwang.wang/20200903114709.png" srcset="/img/loading.gif"></p>
<p>然后任务队列我们也分为<code>微任务队列</code>和<code>宏任务队列</code></p>
<h3 id="1-宏任务队列"><a href="#1-宏任务队列" class="headerlink" title="1.宏任务队列"></a><font style="font-size:2rem;color:red">1.宏任务队列</font></h3><p>常见的宏任务操作:</p>
<ul>
<li>IO 操纵</li>
<li>setTimeout/setInterval/setImmediate 定时器相关</li>
<li>requestAnimationFrame 关键帧动画</li>
</ul>
<p><img src="http://qiniuyun.quancundexiwang.wang/20200903142016.png" srcset="/img/loading.gif"><br>宏任务特性:</p>
<ul>
<li>宏任务所处的队列就是宏任务队列</li>
<li>第一个宏任务队列中只有一个任务：执行主线程上的JS代码；如果遇到上方中的异步任务，会创建出一个新的宏任务队列，存放这些异步函数执行完成后的回调函数。</li>
<li>宏任务队列<code>可以有多个</code></li>
<li>宏任务中<code>可以创建微任务</code>，但是在宏任务中<code>创建的微任务不会影响当前宏任务的执行</code>。</li>
<li>当一个宏任务队列中的任务全部执行完后，会查看是否有微任务队列，如果有就会优先执行微任务队列中的所有任务，如果没有就查看是否有宏任务队列。<h3 id="2-微任务队列"><a href="#2-微任务队列" class="headerlink" title="2.微任务队列"></a><font style="font-size:2rem;color:red">2.微任务队列</font></h3><img src="http://qiniuyun.quancundexiwang.wang/20200903143244.png" srcset="/img/loading.gif"></li>
</ul>
<p><img src="http://qiniuyun.quancundexiwang.wang/20200903142102.png" srcset="/img/loading.gif"></p>
<h3 id="3-实例帮助理解"><a href="#3-实例帮助理解" class="headerlink" title="3.实例帮助理解"></a><font style="font-size:2rem;color:red">3.实例帮助理解</font></h3><p>其实这个东西，我一直不太理解，看了一位大佬讲的实际生活的对照，多少对理解有点帮助。</p>
<blockquote>
<p>就像去银行办业务一样，先要取号进行排号。</p>
</blockquote>
<p><img src="http://qiniuyun.quancundexiwang.wang/20200903143440.png" srcset="/img/loading.gif"></p>
<blockquote>
<p>一般上边都会印着类似：“您的号码为XX，前边还有XX人。”之类的字样。<br>因为<code>柜员同时职能处理一个来办理业务的客户</code>，这时<code>每一个来办理业务的人就可以认为是银行柜员的一个宏任务来存在的</code>，当柜员处理完当前客户的问题以后，<code>选择接待下一位，广播报号，也就是下一个宏任务的开始。</code><br>所以<code>多个宏任务合在一起就可以认为说有一个任务队列在这</code>，<code>里边是当前银行中所有排号的客户</code>。</p>
</blockquote>
<blockquote>
<p>任务队列中的都是<code>已经完成的异步操作</code>，而<code>不是说注册一个异步任务就会被放在这个任务队列中</code>，就像在<code>银行中排号，如果叫到你的时候你不在，那么你当前的号牌就作废</code>了，柜员会选择直接跳过进行下一个客户的业务处理，等你回来以后还需要重新取号</p>
</blockquote>
<blockquote>
<p>而且一个<code>宏任务在执行的过程中，是可以添加一些微任务的</code>，就像在柜台办理业务，你前边的一位老大爷可能在存款，在存款这个业务办理完以后，<code>柜员会问老大爷还有没有其他需要办理的业务</code>，这时老大爷想了一下：“最近P2P爆雷有点儿多，是不是要选择稳一些的理财呢”，然后告诉柜员说，要办一些理财的业务，这时候柜员肯定不能告诉老大爷说：“您再上后边取个号去，重新排队”</p>
</blockquote>
<blockquote>
<p><code>所以本来快轮到你来办理业务，会因为老大爷临时添加的“理财业务”而往后推。也许老大爷在办完理财以后还想 再办一个信用卡？或者 再买点儿纪念币？无论是什么需求，只要是柜员能够帮她办理的，都会在处理你的业务之前来做这些事情，这些都可以认为是微任务</code>。这就说明：你大爷永远是你大爷<code>在当前的微任务没有执行完成时，是不会执行下一个宏任务的。</code></p>
</blockquote>
<p><font style="font-size:2rem;color:red">看完这个故事再去看微任务的流程图 真的理解了！！！</font></p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
       console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"宏任务-定时器任务1"</span><span class="token punctuation">)</span>
   <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
   <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">reslove<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
       <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
           console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"宏任务-定时器任务2"</span><span class="token punctuation">)</span>
       <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
       <span class="token function">reslove</span><span class="token punctuation">(</span><span class="token string">"成功"</span><span class="token punctuation">)</span>
   <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">res</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
       console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"取钱-微任务"</span><span class="token punctuation">)</span>
   <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
       console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"p2p-微任务"</span><span class="token punctuation">)</span>
   <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
   console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"同步代码"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>运行结果<br><img src="http://qiniuyun.quancundexiwang.wang/20200903145523.png" srcset="/img/loading.gif"><br>简单解析<br><img src="http://qiniuyun.quancundexiwang.wang/20200903145011.png" srcset="/img/loading.gif"></p>
<p>现在看看那个经常在面试题、各种博客中的代码片段：</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token parameter">_</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token parameter">resolve</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">_</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><code>setTimeout就是作为宏任务来存在的</code>，而<code>Promise.then则是具有代表性的微任务</code>，上述代码的执行顺序就是按照序号来输出的。</p>
<p><code>new Promise</code>在实例化的过程中所执行的代码都是<code>同步进行</code>的，而<code>then中注册的回调才是异步执行</code>的。</p>
<p><code>同步代码执行完成后才回去检查是否有异步任务完成</code>，并执行<code>放入任务队列中的对应的回调函数</code>，而<code>微任务又会在宏任务之前执行。</code></p>
<p>所以就得到了上述的输出结论1、2、3、4。</p>
<h3 id="4-Event-Loop事件循环"><a href="#4-Event-Loop事件循环" class="headerlink" title="4.Event-Loop事件循环"></a><font style="font-size:2rem;color:red">4.Event-Loop事件循环</font></h3><blockquote>
<p>上边一直在讨论 宏任务、微任务，各种任务的执行。但是回到现实，JavaScript是一个<code>单进程的语言</code>，<code>同一时间不能处理多个任务</code>，所以何时执行宏任务，何时执行微任务？我们需要有这样的一个<code>判断逻辑</code>存在。</p>
</blockquote>
<ul>
<li>每办理完一个业务，柜员就会问当前的客户，是否还有其他需要办理的业务。（<code>检查还有没有微任务需要处理</code>）</li>
<li>而客户明确告知说没有事情以后，柜员就去查看后边还有没有等着办理业务的人。（<code>结束本次宏任务、检查还有没有宏任务需要处理</code>）</li>
</ul>
<blockquote>
<p>这个检查的过程是持续进行的，每完成一个任务都会进行一次，而这样的操作就被称为Event Loop。(这是个非常简易的描述了，实际上会复杂很多)</p>
</blockquote>
<h2 id="3-手写Promise（晚点写）"><a href="#3-手写Promise（晚点写）" class="headerlink" title="3.手写Promise（晚点写）"></a>3.手写Promise（晚点写）</h2><p><img src="https://cdn.jsdelivr.net/gh/changhao970630/cdn@master/images/20200901155012.gif" srcset="/img/loading.gif"></p>
<p><img src="https://cdn.jsdelivr.net/gh/changhao970630/cdn@master/images/20200901155201.gif" srcset="/img/loading.gif"></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JavaScript%E5%9F%BA%E6%9C%AC%E5%8A%9F/">JavaScript基本功</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/posts/23665/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">HTML-Interview</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/posts/15960/">
                        <span class="hidden-mobile">动画Svg(loading,background)1⃣️</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    Fluid.utils.waitElementVisible('vcomments', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz",
          app_key: "hMuhiD4FRqhns4giqLiEH9HG",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the
    <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments powered by Valine.</a>
  </noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    

  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        豫ICP备20009912号-1
      </a>
    </span>
    
  </div>


  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":true,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  
    
  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "http://qiniuyun.quancundexiwang.wang/xmlSearch.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
